<template>
  <x-main>
    <x-table ref="table" :isPage="true" @search="onSearch" @auth="onAuth" @modify="onModify" @remove="onRemove" @assignUser="onAssignUser">
      <template v-slot:btn-tool>
        <el-button type="primary" @click="onAdd">新增</el-button>
      </template>
      <template #status="scope">
        <el-switch @click="onClick(scope.data)" v-model="scope.data.status" :active-value="0" :inactive-value="1"></el-switch>
      </template>
    </x-table>
  </x-main>
</template>

<script setup name="sys-role-index">
import useStore from '@/stores/modules/sys/role';
const sysRole = useStore();
import XForm from "./Form.vue";
import XUser from "./User.vue";

import {onMounted, ref} from "vue";
import XMenu from "./Menu";

onMounted(() => {
  sysRole.init(table)
  sysRole.getList(1, 10);
})

let table = ref();

/**
 * 搜索
 * @param pageNo
 * @param pageSize
 * @param condition
 */
const onSearch = (pageNo, pageSize, condition) => {
  sysRole.getList(pageNo, pageSize, condition);
}

/**
 * 状态切换
 * @param row
 */
const onClick = (row) => {
  let status = row.status
  let msg = status == 1 ? "是否禁用该角色" : "是否启用该角色"

  Msg.confirm(msg).then(async _ => {
    let success = status == 1 ? await sysRole.disabled({id: row.id}) : await sysRole.enabled({id: row.id})
    if (! success) {
      row.status = row.status == 0 ? 1 : 0;
    }
  }).catch(err => {
    row.status = row.status == 0 ? 1 : 0;
  })
}

/**
 * 新增
 * @returns {Promise<void>}
 */
const onAdd = async () => {
  open(XForm, "添加角色", {}, 600)
}

/**
 * 修改
 * @param row
 * @returns {Promise<void>}
 */
const onModify = async (row) => {
  let info = await sysRole.getInfo(row.roleId);
  if (! info) {
    return
  }

  open(XForm, "修改角色", info, 600)
}

const onAuth = async (row) => {
  let info = await sysRole.getInfo(row.roleId);
  if (! info) {
    return
  }

  const op = Dialog.open(XMenu, "授权")
  op.setWidth(1100)
  op.autoClose(true)

  op.mounted(c => {
    c.render(info.menuList)
  })

  op.confirm(c => {
    let menuList = c.getData()
    sysRole.setAuth(row.roleId, menuList.join(","));
  })
}

/**
 * 分配用户
 * @param row
 */
const onAssignUser = async (row) => {
  let info = await sysRole.getInfo(row.roleId);
  if (! info) {
    return
  }

  const op = Dialog.open(XUser, "分配用户")
  op.setWidth(1100)
  op.setConfirmText(false)

  op.mounted(c => {
    c.render(info)
  })
}

/**
 * 删除
 * @param row
 */
const onRemove = (row) => {
  Msg.confirm("确认删除该数据？").then(_ => {
    sysRole.remove(row.id)
  })
}

const open = (component, title, data, width) => {
  const op = Dialog.open(component, title)
  op.setWidth(width)

  op.mounted(c => {
    c.render(data)
  })

  op.confirm(c => {
    c.submit()
  })
}
</script>
